﻿using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
namespace InstallationClient.Mqtt {
    /// <summary>
    /// 
    /// </summary>
    public class MqttClientHelper {
        private IMqttClient _mqttClient;
        private string _clientId;
        private string _host;
        private int _port;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="port">端口</param>
        /// <param name="clientId">客户端ID</param>
        public MqttClientHelper(string host, int port, string clientId) {
            _host = host;
            _port = port;
            _clientId = clientId;
            _mqttClient = new MqttFactory().CreateMqttClient();
        }
        /// <summary>
        /// 是否已连接
        /// </summary>
        public bool IsConnected {
            get {
                return _mqttClient.IsConnected;
            }
        }

        /// <summary>
        /// 连接MQTT服务器
        /// </summary>
        /// <returns></returns>
        public async Task ConnectAsync() {
            var options = new MqttClientOptionsBuilder()
                .WithClientId(_clientId)
                .WithTcpServer(_host, _port)
                .Build();

            await _mqttClient.ConnectAsync(options);
        }
        /// <summary>
        /// 断开MQTT服务器
        /// </summary>
        /// <returns></returns>
        public async Task DisconnectAsync() {
            if (_mqttClient.IsConnected) {
                await _mqttClient.DisconnectAsync();
            }
        }
        /// <summary>
        /// 订阅主题(接收消息)
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="messageReceivedHandler"></param>
        /// <returns></returns>
        public async Task SubscribeAsync(string topic, Func<MqttApplicationMessageReceivedEventArgs, Task> messageReceivedHandler) {

            _mqttClient.ApplicationMessageReceivedAsync += messageReceivedHandler;

            await _mqttClient.SubscribeAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce);

        }
        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task PublishAsync(string topic, string message) {
            var mqttMessage = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(message)
                //.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                .Build();

            await _mqttClient.PublishAsync(mqttMessage);
        }
    }

    /// <summary>
    /// 指令枚举
    /// </summary>
    public enum MqttDirective {
        /// <summary>
        /// 备份SQLServer数据库
        /// </summary>
        BaackupMSSQL = 1,
    }
}